﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using WcfFlashRemoting.ServiceModel.Channels;

namespace WcfFlashRemoting.ServiceModel.Dispatcher
{
    class AmfMultipleOperationFormatter : IDispatchMessageFormatter
    {
        #region IDispatchMessageFormatter Members

        public void DeserializeRequest(System.ServiceModel.Channels.Message message, object[] parameters)
        {
            AmfMultipleMessage msg = message as AmfMultipleMessage;
            if (msg == null)
            {
                throw new InvalidOperationException("AmfMultipleMessage required for AmfMultipleOperationFormatter");
            }
            if (System.ServiceModel.OperationContext.Current != null)
            {
                // TODO - here we have access to the Message Properties and the OperationContext.  HERE we can register something for logging.
                System.ServiceModel.OperationContext.Current.IncomingMessageProperties.Add("AmfMessageHeaders", msg.AmfHeaders);
                System.ServiceModel.OperationContext.Current.IncomingMessageProperties.Add("AmfMessageBodies", msg.AmfBodies);
            }
            parameters[0] = msg.AmfBodies.Select(body => new AmfMessage(msg.Version, msg.AmfHeaders, body, msg.AmfVersion));
        }

        public System.ServiceModel.Channels.Message SerializeReply(System.ServiceModel.Channels.MessageVersion messageVersion, object[] parameters, object result)
        {
            Dictionary<string, WcfFlashRemoting.AmfObjects.AmfHeader> headers = new Dictionary<string,WcfFlashRemoting.AmfObjects.AmfHeader>();
            foreach (AmfMessage msg in (result as List<AmfMessage>))
            {
                foreach (WcfFlashRemoting.AmfObjects.AmfHeader header in msg.AmfHeaders)
                {
                    headers[header.Name] = header;
                }
            }
            return new AmfMultipleMessage(
                messageVersion, 
                headers.Values.ToArray(),
                (result as List<AmfMessage>).Select(m => m.AmfBody).ToArray(), 
                AmfBaseMessage.GetCurrentAmfVersion);
        }

        #endregion
    }
}
